package com.iotek.bookstore.web.controlle;

import com.iotek.bookstore.modle.entity.TitleOne;
import com.iotek.bookstore.modle.entity.TitleTwo;
import com.iotek.bookstore.modle.service.serviceimpl.TitleOneBizImpl;
import com.iotek.bookstore.modle.service.serviceimpl.TitleTwoBizImpl;
import net.sf.json.JSON;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/login/titleServlet")
public class TitleServlet extends CommonServlet {
    @Override
    public void doInsert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            int titleOneId=Integer.parseInt(req.getParameter("titleOneId"));
            String title=req.getParameter("title");
            TitleTwo titleTwo=new TitleTwo();
            titleTwo.setTitleOneId(titleOneId);
            titleTwo.setTitle(title);
            if(new TitleTwoBizImpl().insert(titleTwo)==0){
                resp.getWriter().write("0");
            }else {
                resp.getWriter().write("1");
            }
    }

    @Override
    public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            int id=Integer.parseInt(req.getParameter("id"));
            if(new TitleTwoBizImpl().delete(id)==0){
                resp.getWriter().write("0");
            }else {
                resp.getWriter().write("1");
            }
    }

    @Override
    public void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            int id=Integer.parseInt(req.getParameter("id"));
            String title=req.getParameter("title");
            TitleTwo titleTwo=new TitleTwo();
            titleTwo.setId(id);
            titleTwo.setTitle(title);
            if(new TitleTwoBizImpl().update(titleTwo)==0){
                resp.getWriter().write("0");
            }else {
                resp.getWriter().write("1");
            }
    }

    @Override
    public void doQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type=req.getParameter("type");
        if(type==null){
            List<TitleTwo>titleTwos=new TitleTwoBizImpl().queryAll();
            JSON json= JSONArray.fromObject(titleTwos);
            System.out.println("信息来自-->TitleServlet---->doQuery:");
            System.out.println(json.toString());
            resp.getWriter().write(json.toString());
        }else {
            List<TitleOne>titleOnes=new TitleOneBizImpl().queryAll();
            JSON json=JSONArray.fromObject(titleOnes);
            System.out.println("信息来自-->TitleServlet---->doQuery:");
            System.out.println(json.toString());
            resp.getWriter().write(json.toString());
        }

    }
}
